package com.atstudent.gmall.order.listener;/*
 * @author: XueYouPeng
 * @time: 23.9.18 下午 9:24
 */

import com.alibaba.fastjson.JSON;
import com.atstudent.gmall.order.service.OrderInfoService;
import com.atstudent.gmall.rabbit.constant.RabbitConstant;
import com.atstudent.gmall.rabbit.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class OrderCloseListener {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RabbitService rabbitService ;

    @RabbitListener(queues = RabbitConstant.ORDER_DELAY_QUEUE)
    public void orderDelayQueueListener(Message message , Channel channel){

        MessageProperties properties = message.getMessageProperties();
        long deliveryTag = properties.getDeliveryTag();

        byte[] body = message.getBody();
        String msgJSON = new String(body);

        try {
            Map<String , String> map = JSON.parseObject(msgJSON, Map.class);
            String orderId = map.get("orderId");
            String userId = map.get("UserId");
            //调用关单的接口
            orderInfoService.closeOrder(Long.parseLong(orderId) , Long.parseLong(userId));
            log.info("消息被正常消费了....");

            /**
             * deliveryTag: 消息的标签，通过该值就可以确定消息的唯一性
             * multiple：   表示是否需要进行批量应答
             */
            channel.basicAck(deliveryTag , true);
        } catch (IOException e) {
            e.printStackTrace();
            rabbitService.retry(channel , deliveryTag , msgJSON , 5);
        }
    }
}
